using System;
using System.Html;
using System.Runtime.CompilerServices;

namespace Nsb.Classes
{
    [IgnoreNamespace]
    public class PkgBase : FileBlobBase
    {
        private readonly bool _storeLcl;
        public const string ResultRx = "result";


        protected PkgBase()
        {
            _storeLcl = false;
        }

        /*
        protected void AppendPkgStringAw(Await awp, string partitionKey, string rowKey, string rxKey, string pkg)
        {
            new Await()
                .AddDl(
                    delegate(Await aw)
                    {
                        AppendLcl(partitionKey, rowKey, pkg);
                        AppendBlobStringAw(aw, partitionKey, rowKey, rxKey, pkg);
                    })
                .HandleDl(Exceptions.BlobSaveError, Await.AbortAw)
                .AddDx(delegate(Await aw) { Inform.Log("Package appended partiton={0}, row={1}, result={2}", partitionKey, rowKey, aw[rxKey]); })
                .Commit(awp);
        }

        protected void PutPkgStringAw(Await awp, string partitionKey, string rowKey, string rxKey, string pkg)
        {
            new Await()
                .AddDl(
                    delegate(Await aw)
                    {
                        Window.LocalStorage.SetItem(rowKey, pkg);
                        StoreBlobStringAw(aw, partitionKey, rowKey, rxKey, pkg);
                    })
                .AddDx(delegate(Await aw) { Inform.Log("Package stored partiton={0}, row={1}, result={2}", partitionKey, rowKey, aw[rxKey]); })
                .Commit(awp);
        }

        protected void GetPkgStringAw(Await awp, string partitionKey, string rowKey, string rxKey)
        {
            new Await()
                .AddDx(delegate(Await aw) { aw["svd"] = GetLcl(partitionKey, rowKey); })
                .AddDl(delegate(Await aw) { RetrieveBlobStringAw(aw, partitionKey, rowKey, rxKey); })
                .HandleDl(Exceptions.BlobLoadError, Await.RethrowAw)
                .AddDx(delegate(Await aw) { awp[rxKey] = Script.Value((string)aw[rxKey], (string)aw["svd"]); })
                .Commit(awp);
        }
        */
        public void AppendLcl(string partitionKey, string rowKey, string content)
        {
            if (!_storeLcl)
                return;
            string pkg = (string)Window.LocalStorage.GetItem(rowKey) ?? "";
            string jsonPkg = pkg + (String.IsNullOrEmpty(pkg) ? "" : ",") + content;
            Window.LocalStorage.SetItem(partitionKey + rowKey, jsonPkg);
        }

        public string GetLcl(string partitionKey, string rowKey)
        {
            if (!_storeLcl)
                return null;
            return (string)Window.LocalStorage.GetItem(partitionKey + rowKey);
        }

    }
}